﻿@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_Index.cshtml";
}
@using Raffles.OA.Data
@using Raffles.OA.Utility 
<link href="~/Content/plugin/bootstrap.daterangepicker/daterangepicker.min.css" rel="stylesheet" />
<link href="~/Content/sale/css/project.css" rel="stylesheet" />
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-header" id="searchDiv">
                    <div class="col-md-2 col-xs-12">
                        <div class="input-group">
                            <div class="input-group-addon">关键字</div>
                            <input type="text" id="keyWord" col="KeyWord" class="form-control" placeholder="请输入关键字查询" />
                        </div>
                    </div>
                    <div class="col-md-3 col-xs-12">
                        <div class="input-group">
                            <div class="input-group-addon">出团日期</div>
                            <input type="hidden" id="departureDateStart" col="DepartureDateStart" />
                            <input type="hidden" id="departureDateEnd" col="DepartureDateEnd" />
                            <input type='text' class="form-control" placeholder="请选择日期" id="DepartureDate" />
                        </div>
                    </div>
                    <div class="col-md-3 col-xs-12">
                            <div class="input-group">
                                <div class="input-group-addon">项目状态</div>
                                <select id="status" col="Status" class="form-control">
                                    <option value="">全部</option>
                                </select>
                            </div>
                        </div>
                    <div class="col-md-3 col-xs-12">
                        <div class="input-group">
                            <div class="input-group-addon">销售人员</div>
                            <select id="salerId" col="SalerId" class="form-control">
                                <option value="">全部</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-1 col-xs-12 text-center pull-right">
                        <a href="javascript:void(0);" authorize="yes" id="btnProjectCommisionSearch" class="btn btn-primary btn-sm" onclick="searchGrid()"><i class="fa fa-search"></i> 查询</a>
                    </div>
                </div>
            </div>
            <div class="box box-info">
                <div class="box-body">
                    <div class="table-responsive">
                        <div class="btn-group-sm" id="toolbar" role="group">
                            <a href="javascript:void(0);" authorize="yes" id="btnCloseProject" class="btn btn-success btn-xs disabled" onclick="closeProject()"><i class="fa fa-window-close-o"></i> 项目关闭</a>
                            <a href="javascript:void(0);" authorize="yes" id="btnEditOperateRate" class="btn btn-info btn-xs disabled" onclick="editOperateRate()"><i class="fa fa-edit"></i> 修改操作率</a>
                            <a href="javascript:void(0);" authorize="yes" id="btnBackProjectFinance" class="btn btn-danger btn-xs disabled" onclick="backProject()"><i class="fa fa-backward"></i> 项目退回</a>
                            <div class="col-sm-3 pull-right">
                                <div class="input-group input-group-sm">
                                    <div class="input-group-btn">
                                        <label class="form-control text-green fontnumber" id="totalCommision" style="border:none;text-align:end;padding-right:30px"></label>
                                    </div>
                                </div>
                            </div>
                        </div> 
                        <table id="gridTable" class="table table-hover text-nowrap">
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<script src="~/Content/plugin/bootstrap.daterangepicker/daterangepicker.min.js"></script>
<script src="/Content/plugin/bootstrap.datepicker/js/moment-with-locales.js"></script>
<script type="text/javascript">

    $(function () {
        $("#status").frameSelect({
            data: frame.getJson(@Html.Raw(typeof(ProjectStatusEnum).EnumToDictionaryString())),
            default:[@((int)ProjectStatusEnum.Done)]
        });
        $("#salerId").frameSelect({
            url: "@Url.Action("GetSalerSelect", "Project",new { area = "Sale" })"
        });
        $('#departureDateStart').val(moment().startOf('year').format('YYYY-MM-DD'));
        $('#departureDateEnd').val(moment().endOf('year').format('YYYY-MM-DD'));
        $('#DepartureDate').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD'
            },
            startDate: moment().startOf('year'),
            endDate: moment().endOf('year')
        }).on('apply.daterangepicker', function (ev, picker) {
            $('#departureDateStart').val(picker.startDate.format('YYYY-MM-DD'));
            $('#departureDateEnd').val(picker.endDate.format('YYYY-MM-DD'));
        }).on('cancel.daterangepicker', function (ev, picker) {
            // 重置选择器的值为默认值
            picker.setStartDate(moment().startOf('year'));
            picker.setEndDate(moment().endOf('year'));
            // 更新输入框的值
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            $('#departureDateStart').val(moment().startOf('year').format('YYYY-MM-DD'));
            $('#departureDateEnd').val(moment().endOf('year').format('YYYY-MM-DD'));
        });
        initGrid();
        resetBootstrapTableView('gridTable', 109);
        $("#gridTable").on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table", function () {
            var rows = $("#gridTable").bootstrapTable("getSelections");
            if ($('#btnCloseProject')) {
                $('#btnCloseProject').toggleClass('disabled', !rows.length);
            }
            if ($('#btnEditOperateRate')) {
                $('#btnEditOperateRate').toggleClass('disabled', rows.length != 1);
            }
            if ($('#btnBackProjectFinance')) {
                $('#btnBackProjectFinance').toggleClass('disabled', rows.length != 1);
            }
        });
    });

    function initGrid() {
        $('#gridTable').frameTable({
            url: '@Url.Action("GetCommisionPageListJson", "Project")',
            sortName: 'CreatedOn',
            sortOrder: 'desc',
            striped: false,
            singleSelect: true,
            columns: [
                {
                    checkbox: true, visible: true,
                    @*formatter: function (value, row, index) {
                        //只可操作已完成的项目
                        if (row.Status == @((int)ProjectStatusEnum.Done)) {
                            return {
                                disabled: false
                            };
                        }
                        else {
                            return {
                                disabled: true
                            };
                        }
                    }*@
                },
                { field: 'Id', title: 'Id', visible: false },
                {
                    field: 'Status', title: '项目状态', halign: "center", align: "center",
                    formatter: function (value, row, index) {
                        switch (value) {
                            case @((int)ProjectStatusEnum.Done):
                                return '<span class="label label-warning">@ProjectStatusEnum.Done.GetDescription()</span> ';
                            case @((int)ProjectStatusEnum.Closed):
                                return '<span class="label label-success">@ProjectStatusEnum.Closed.GetDescription()</span> ';
                        }
                    }
                },
                {
                    field: 'Name', title: '项目名称', halign: "center", align: "center"
                },
                {
                    field: 'DepartureDate', title: '行程日期', halign: "center", align: "center", sortable: true,
                    formatter: function (value, row, index) {
                        return "<span class='text-red text-bold font'>" + moment(row.DepartureDate).format('YYYY.MM.DD') + " - " + moment(row.ReturnDate).format('YYYY.MM.DD') +"</span>";
                    }
                },
                {
                    field: '', title: '营业收入', halign: "left", align: "left",
                    formatter: function (value, row, index) {
                        return row.SettlementCurrency + "：<span class='text-bold text-green fontnumber underline'>" + frame.formatCurrency(row.SaleSGDAmountAfterTax, "USD") + "</span>" + "<br />" +
                            "RMB：<span class='text-bold text-red fontnumber underline'>" + frame.formatCurrency(row.SaleRMBAmountAfterTax, "CNY") + "</span>" + "</span>";
                    }
                },
                {
                    field: '', title: '项目成本(RMB)', halign: "left", align: "left",
                    formatter: function (value, row, index) {
                        return "销售成本：<span class='text-bold text-green fontnumber underline'>" + frame.formatCurrency(row.CostRMBAmountAfterTax, "CNY") + "</span>" + "<br />" +
                            "运营成本：<span class='text-bold text-red fontnumber underline'>" + frame.formatCurrency(row.TotalOperateCostAmount, "CNY") + "</span>";
                    }
                },
                {
                    field: '', title: '销售利润(RMB)', halign: "left", align: "left",
                    formatter: function (value, row, index) {
                        var moneyMake, moneyMakeFull = 0;
                        if (row.SaleRMBAmountAfterTax > 0) {
                            var moneyMakeFull = row.SaleRMBAmountAfterTax - row.CostRMBAmountAfterTax - row.TotalOperateCostAmount - row.SalerCommissionAmount;//销售净利=收入-成本-运营成本-提成
                            var moneyMake = row.SaleRMBAmountAfterTax - row.CostRMBAmountAfterTax;//销售毛利
                        }
                        return "净利：<span class='text-bold text-green fontnumber underline'>" + frame.formatCurrency(moneyMakeFull, "CNY") + "</span>" + "<br />" +
                            "毛利：<span class='text-bold text-red fontnumber underline'>" + frame.formatCurrency(moneyMake, "CNY") + "</span>";

                    }
                },
                {
                    field: '', title: '毛利润率(%)', halign: "center", align: "center",
                    formatter: function (value, row, index) {
                        var moneyMakeRate = 0;
                        if (row.SaleRMBAmountAfterTax > 0) {
                            var moneyMakeRate = (row.SaleRMBAmountAfterTax - row.CostRMBAmountAfterTax) / row.SaleRMBAmountAfterTax * 100;
                        }
                        if (moneyMakeRate >= 0) {
                            return "<span class='text-bold text-green fontnumber underline'>" + (moneyMakeRate.toFixed(2)) + "%</span>" + "</span>";
                        }
                        else {
                            return "<span class='text-bold text-red fontnumber underline'>" + (moneyMakeRate.toFixed(2)) + "%</span>" + "</span>";
                        }


                    }
                },
                {
                    field: 'SaleManagerName', title: '销售经理', halign: "center", align: "center"
                },
                {
                    field: 'OperateRate', title: '销售操作率', halign: "center", align: "center",
                    formatter: function (value, row, index) {
                        if (value >=1 ) {
                            return value;
                        } else {
                            return value * 100 + "%";
                        }
                    }
                },
                {
                    field: 'SalerCommissionAmount', title: '销售提成', halign: "center", align: "center",
                    formatter: function (value, row, index) {
                        if (value >= 0) {
                            return "<a class='text-bold text-green fontnumber underline'>" + frame.formatCurrency(value, "CNY") + "</a>";
                        }
                        return "<a class='text-bold text-red fontnumber underline'>" + frame.formatCurrency(value, "CNY") + "</a>";
                    }
                }
            ],
            queryParams: function (params) {
                var pagination = $('#gridTable').frameTable('getPagination', params);
                var queryString = $('#searchDiv').getWebControls(pagination);
                return queryString;
            },
            onPostBody: function (data) {
                if (data.length > 0) {
                    var totalCommision = data.reduce((total, obj) => total += obj.SalerCommissionAmount, 0)
                    $('#totalCommision').text(frame.formatCurrency(totalCommision, "CNY"));
                }
            }
        });
    }

    function searchGrid() {
        $('#gridTable').frameTable('search');
        resetButtonStatus();
    }

    function resetButtonStatus() {
        if ($('#btnCloseProject')) {
            $('#btnCloseProject').addClass('disabled');
        }
        if ($('#btnEditOperateRate')) {
            $('#btnEditOperateRate').addClass('disabled');
        }
        if ($('#btnBackProjectFinance')) {
            $('#btnBackProjectFinance').addClass('disabled');
        }
    }

    //项目关闭
    function closeProject() {
        var selectedRow = $("#gridTable").bootstrapTable("getSelections");
        if (frame.checkRowDelete(selectedRow)) {
            frame.confirm("确认要关闭选中的[<span class='text-bold text-red'>" + selectedRow.length + "</span>]个项目吗？", function () {
                var ids = frame.getIds(selectedRow);
                frame.ajax({
                    url: '@Url.Content("/Finance/Project/CloseProject")' + '?ids=' + ids,
                    type: "post",
                    success: function (obj) {
                        if (obj.success) {
                            frame.msgSuccess(obj.message);
                            searchGrid();
                        }
                        else {
                            frame.msgError(obj.message);
                        }
                    }
                });
            });
        }
    }

    //销售操作率
    function editOperateRate() {
        var id = 0;
        var selectedRow = $("#gridTable").bootstrapTable("getSelections");
        if (!frame.checkRowEdit(selectedRow)) {
            return;
        }
        else {
            id = selectedRow[0].Id;
        }
        frame.openDialog({
            title: '修改销售操作率',
            content: '@Url.Content("/Finance/Project/OperateRateForm")' + '?projectId=' + id,
            width: '500px',
            height: '350px',
            callback: function (index, layero) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                iframeWin.saveOperateRate(index);
            }
        });
    }
    //项目退回
    function backProject() {
        var id = 0;
        var selectedRow = $("#gridTable").bootstrapTable("getSelections");
        if (!frame.checkRowEdit(selectedRow)) {
            return;
        }
        else {
            id = selectedRow[0].Id;
        }
        frame.confirm("确定退回到财务吗？", function () {
            frame.ajax({
                url: '@Url.Content("/Finance/Project/BackProjectFinance")' + '?projectId=' + id,
                type: "post",
                success: function (obj) {
                    if (obj.success) {
                        frame.msgSuccess(obj.message);
                        searchGrid();
                    }
                    else {
                        frame.msgError(obj.message);
                    }
                }
            });
        });
    }
</script>